//
//  ConfirmOrderViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/28.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "ConfirmOrderViewController.h"
#import "MLoctionCell.h"
#import "ConfirmCell.h"
#import "ManagerLoctaionViewController.h"
#import "PayWayView.h"
#import "AddLoctionViewController.h"
#import "ShopCartHeadView.h"
#import "GoodsDetailViewController.h"
@interface ConfirmOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableV;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UILabel *totalBalance;
@property (weak, nonatomic) IBOutlet UILabel *topLabel;
@property (weak, nonatomic) IBOutlet UIButton *topButtton;
@property (weak, nonatomic) IBOutlet UIImageView *topImageV;
@property(nonatomic,strong)PayWayView *pv;
@property(nonatomic,assign)NSInteger  sectionCount;
@property(nonatomic,assign)BOOL isEditeLocation;
@end

@implementation ConfirmOrderViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter ]removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.vcName = @"确认订单";
    [self tableViewAndHeaderView];
//    [self getAddressInfo];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeReceiveAddress:) name:@"changeReceiveAddress" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AddReceiveAddress:) name:@"AddReceiveAddress" object:nil];
}

-(void)setTotalMoney:(NSString *)totalMoney{
    _totalMoney  = totalMoney;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.isEditeLocation){
        self.isEditeLocation = NO;
        return;
    }
     [self getAddressInfo];
}
//重新选择收货地址或者是编辑收货地址后收到的通知事件
-(void)changeReceiveAddress:(NSNotification*)noti{
    self.isEditeLocation = YES;
    LocationModel *model= noti.object;
    ShopCartGroup *group = [[ShopCartGroup alloc]init];
    group.storeName = @"收件人信息";
    NSMutableArray *arr = [NSMutableArray array];
    [arr addObject:model];
    group.shopCartModels = arr;
    [self.dataSource replaceObjectAtIndex:0 withObject:group];
    [self.tableV reloadData];
}
//添加收货地址后的通知
-(void)AddReceiveAddress:(NSNotification*)noti{
    [self getAddressInfo];
}

-(void)setDataSource:(NSMutableArray *)dataSource{
    _dataSource = dataSource;
    self.sectionCount = _dataSource.count;
}

-(void)getAddressInfo{
    //2.29点击商品立即购买跳转确认订单界面后调用的接口
    NSDictionary *paraDic = @{
                              @"userId":USERID
                              };
    __weak typeof(self) weakSelf = self;
//    [MBProgressHUD showActivityMessageInWindow:@""];
    [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:GETADDRESSINFO paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"点击商品立即购买跳转确认订单界面后调用的接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *ldic = resultDic[@"data"];
            if(![ldic[@"address"] length]){
                weakSelf.topImageV.hidden = NO;
                weakSelf.topButtton.hidden = NO;
                weakSelf.topLabel.text = @"请选择收货地址";
                weakSelf.tableV.top = self.topView.bottom+5;
                if(weakSelf.dataSource.count!=self.sectionCount){
                    [weakSelf.dataSource removeObjectAtIndex:0];
                }
                [weakSelf.tableV reloadData];
                [MBProgressHUD dismissHUD];
                return ;
            }else{
                ShopCartGroup *group = [[ShopCartGroup alloc]init];
                group.storeName = @"收件人信息";
                NSMutableArray *arr = [NSMutableArray array];
                LocationModel *model = [[LocationModel alloc]init];
                model.receiverAddress =ldic[@"address"];
                model.receiverPhone = ldic[@"phone"];
                model.receiverName = ldic[@"name"];
                model.isDefault = @"1";
                model.isNeedToHiddenBottomLine = YES;
                [arr addObject:model];
                group.shopCartModels = arr;
                if(weakSelf.dataSource.count==weakSelf.sectionCount){
                     [weakSelf.dataSource insertObject:group atIndex:0];
                }else{
                    [weakSelf.dataSource replaceObjectAtIndex:0 withObject:group];
                }
                weakSelf.topImageV.hidden = YES;
                weakSelf.topButtton.hidden = YES;
                weakSelf.tableV.top = kNaviBarHeight;
                weakSelf.tableV.height = Main_Screen_Height-kNaviBarHeight-49;
                [weakSelf.tableV reloadData];
                [MBProgressHUD dismissHUD];
            }
            weakSelf.totalBalance.text = weakSelf.totalMoney;
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}
- (void)tableViewAndHeaderView{
    //表视图
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.bottom, Main_Screen_Width, Main_Screen_Height-49-self.topView.bottom) style:UITableViewStylePlain];
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = [UIColor colorWithRed:242./255 green:242./255 blue:242./255 alpha:1.];
    _tableV.delegate = self;
    _tableV.dataSource =self;
    [self.view addSubview:_tableV];
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
//    _tableV.scrollEnabled = NO;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ShopCartGroup *group = self.dataSource[section];
    return group.shopCartModels.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0&&self.topImageV.hidden ==YES){
    MLoctionCell    *cell=[[[NSBundle mainBundle]loadNibNamed:@"MLoctionCell" owner:self options:nil]lastObject];
        cell.isConfirmVc = YES;
        cell.imageV.hidden = NO;
        ShopCartGroup *group = self.dataSource[indexPath.section];
        NSMutableArray *rowArray =group.shopCartModels;
        cell.model = rowArray[indexPath.row];
        return cell;
    }
    NSString *ident=@"actell";
    ConfirmCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"ConfirmCell" owner:self options:nil]lastObject];
    }
    ShopCartGroup *group = self.dataSource[indexPath.section];
    NSMutableArray *rowArray =group.shopCartModels;
    ShopCartModel *model = rowArray[indexPath.row];
    cell.model = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0&&self.topImageV.hidden ==YES) return 130;
    return 90;
}

//自定义头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *headID = @"head";
    ShopCartHeadView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
    if(headView==nil){
        headView = [[[NSBundle mainBundle]loadNibNamed:@"ShopCartHeadView" owner:self options:nil]lastObject];
    }
    ShopCartGroup *group =self.dataSource[section];
    if(section==0&&self.topImageV.hidden ==YES){
        group.isNotNeedImageV = YES;
    }
    headView.group =group;
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 32;
}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    NSString *headID = @"footer";
//    ColectFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headID];
//    if(footerView==nil){
//        footerView = [[[NSBundle mainBundle]loadNibNamed:@"ColectFooterView" owner:self options:nil]lastObject];
//    }
//    return footerView;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return 3;
//}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0&&self.dataSource.count!=self.sectionCount){
        ManagerLoctaionViewController *maLoVc= [[ManagerLoctaionViewController alloc]init];
        maLoVc.vcName = @"管理收货地址";
        maLoVc.isChangReceiveAddress = YES;
        [self.navigationController pushViewController:maLoVc animated:YES];
        return;
    }
    
    ShopCartGroup *group =self.dataSource[indexPath.section];
    NSMutableArray *rowArray =group.shopCartModels;
    ShopCartModel *model = rowArray[indexPath.row];

    GoodsDetailViewController *goodsDetail  = [[GoodsDetailViewController alloc]init];
    goodsDetail.pid = model.pId;
    goodsDetail.goodPic = model.pPic;
    goodsDetail.isNeedMessageItem = YES;
    [self.navigationController pushViewController:goodsDetail animated:YES];
}


- (IBAction)commit:(UIButton *)sender {
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
      [window addSubview:self.maskV];
      [window addSubview:self.pv];
     self.maskV.userInteractionEnabled = YES;
    
    __weak typeof (self) weakSelf = self;
    _pv.closeBlock=^{
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.pv removeFromSuperview];
    };
    _pv.alipayBlock=^{
        DLog(@"alipay");
        [weakSelf commitOrder];
        
    };
    _pv.weixinPayBlock=^{
        DLog(@"weixinPay");
    };
}

-(void)commitOrder{
    
    
    
    
}

- (IBAction)selecteLocation:(UIButton *)sender {
    AddLoctionViewController *maLoVc= [[AddLoctionViewController alloc]init];
    maLoVc.vcName = @"新增收货地址";
    maLoVc.isConfirmVcAddAddress = YES;
    maLoVc.isAddVC = YES;
    [self.navigationController pushViewController:maLoVc animated:YES];
}

- (PayWayView *)pv{
    if(_pv==nil){
        _pv =[[[NSBundle mainBundle]loadNibNamed:@"PayWayView" owner:self options:nil]lastObject];
        _pv.layer.cornerRadius = 5;
        _pv.layer.masksToBounds = YES;
        _pv.center = self.view.center;
           }
    return _pv;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
 
}


@end
